<template>
  <BasicModal
    @register="registerModal"
    @cancel="onClose"
    destroyOnClose
    :title="getTitle"
    :showCancelBtn="false"
    :showOkBtn="false"
    :canFullscreen="false"
    :centered="true"
    :width="'90%'"
    :bodyStyle="{ height: 'calc(100vh - 100px)', padding: '3px', overflowY: 'auto' }"
    :loading="loading"
    loadingTip="请稍候，后台努力处理中..."
  >
  <div style="zoom: 1; min-width:1200px; padding: 0 10px 10px; margin-top: 10px;" :style="{height:'calc(100vh - 150px)', overflowY:'auto'}">
    <!--支付信息 2025-08-25 qindl---->
    <table class="orderTable orderTableAlign" id="orderTable">
      <thead>
        <tr>
          <th colspan="10" align="left">审核信息</th>
        </tr>
      </thead>
      <tbody>
        <tr class="h-35px">
          <th width="6%">编号</th>
          <td width="14%"><span id="_id">{{ accountFlow.id }}</span></td>
          <th width="6%">单号</th>
          <td width="14%"><span id="_lsh">{{ accountFlow.orderId }}</span></td>
          <th width="6%">收入</th>
          <td width="14%"><span id="_skje" class="text-red-500" style="font-weight: bold; float: right">{{ toNumber(accountFlow.skje) }}</span></td>
          <th width="6%">{{accountFlow.uncouple == '1' ? '合并人' : '提交人'}}</th>
          <td width="14%"><span id="_lrr">{{ accountFlow.lrr }}</span></td>
          <th width="6%">{{accountFlow.uncouple == '1' ? '合并时间' : '提交时间'}}</th>
          <td width="14%"><span id="_lrsj">{{ accountFlow.lrsj }}</span></td>
        </tr>
        <tr class="h-35px">
          <th>收款银行</th>
          <td><span id="_djm">{{ accountFlow.djm }}</span></td>
          <th>收付时间</th>
          <td><span id="_sksj">{{ accountFlow.sksj }}</span></td>
          <th>支出</th>
          <td><span id="_fkje" class="text-green-500" style="font-weight: bold; float: right">{{ toNumber(accountFlow.fkje) }}</span></td>
          <th>经理审核</th>
          <td><span id="_shr">{{ accountFlow.shrName }}</span></td>
          <th>审核时间</th>
          <td><span id="_shsj">{{ accountFlow.shsj }}</span></td>
        </tr>
        <tr class="h-35px" v-if="accountFlow.sflx == '1' && accountFlow.sffs == '3'">
          <th class="tdRight">入账银行</th>
          <td class="tdLeft"><span id="_djmPid">{{ accountFlow.djmPid }}</span></td>
          <th class="tdRight"></th>
          <td class="tdLeft"><span id="_bz"></span></td>
          <th class="tdRight">入账金额</th>
          <td class="tdLeft"><span id="_jePid" class="text-red-500" style="font-weight: bold; float: right">{{ toNumber(accountFlow.jePid) }}</span></td>
          <th>财务审批</th>
          <td><span id="_spr">{{ accountFlow.sprName }}</span></td>
          <th>审批时间</th>
          <td><span id="_spsj">{{ accountFlow.spsj }}</span></td>
        </tr>
        <tr class="h-35px" v-else>
          <th class="tdRight">备注</th>
          <td class="tdLeft" colspan="3">
            <span id="_bz">{{ accountFlow.bz }}</span>
          </td>
          <th>对方账名</th>
          <td><span id="_spr">{{ accountFlow.dfhm }}</span></td>
          <th>财务审批</th>
          <td><span id="_spr">{{ accountFlow.sprName }}</span></td>
          <th>审批时间</th>
          <td><span id="_spsj">{{ accountFlow.spsj }}</span></td>
        </tr>
      </tbody>
    </table>

    <!--收付项目 2025-08-25 qindl---->
    <div class="listtab1" id="con_menu_1">
      <table class="orderTable" id="acctable">
        <thead>
          <tr>
            <th colspan="13">
              <div>审核操作</div>
              <div id="status_div">
                <span> 第 <b id="_intIndexNum">{{ data.idIndex + 1 }}</b>/<b id="_intTotal">{{ data.listSize }}</b> 条 </span>&nbsp;
                <span> 审核条数:<b id="_intCheck">{{ data.intCheckValue }}</b>&nbsp;&nbsp; 
                  回退条数:<b id="_intDelete">{{ data.intDeleteValue }}</b>&nbsp;&nbsp;
                  <input type="hidden" id="_intCheckValue" value="0" />
                  <input type="hidden" id="_intDeleteValue" value="0" />
                </span>
                <span>类型: <b id="_intSflx" :class="accountFlow.sflx == '2' ? 'text-green-500' : 'text-red-500'">{{ accountFlow.intSflx }}</b>&nbsp;&nbsp;</span>
                <span>方式: <b id="_intSffs" :class="sffsColor">{{ accountFlow.intSffs }}</b>&nbsp;&nbsp;</span>
                <span>审核状态: <b id="_intStat" :style="{ color: statClass }">{{ accountFlow.intStat }}</b>&nbsp;&nbsp;</span>
              </div>
              <div class=""></div>
              <div class="text-right mr-1">
                <a-button
                  type="primary"
                  color="error"
                  @click="handleDeleteRecord"
                  v-if="data.cwhtButtonShow"
                  :disabled="data.cwhtButtonDisable"
                  class="mr-10px">
                  {{ accountFlow.uncouple == '1' && data.stats['stat'] == '2' ? '取消' : '回退' }}
                </a-button>
                <a-button type="primary" @click="getUpRecord" class="mr-10px"> 上一条 </a-button>
                <a-button type="primary" @click="getNextRecord" class="mr-10px"> 下一条 </a-button>
                <a-button type="primary" color="success" @click="flowPayModal" v-if="data.payfinaceShow" :disabled="data.payfinaceDisable">
                  支付
                </a-button>
                <a-button type="primary" color="success" @click="handleCollateRecord" v-if="data.cwshButtonShow" :disabled="data.cwshButtonDisable">
                  审核
                </a-button>
                <!--a-button type="primary" color="warning" @click="handleRollbackRecord" v-if="data.rollbackShow" :disabled="data.rollbackDisable" > 取消 </a-button-->
              </div>
            </th>
          </tr>
        </thead>
      </table>

      <table class="orderTable" id="acctable" v-if="accountFlow.uncouple == '1'"> 
        <thead>
          <tr>
            <th colspan="14" class="bg-red-50">
              <span class="float-left w-200px leading-30px">合并项目</span>
            </th>
          </tr>
        </thead> 
        <tbody>
          <tr class="listBg">
            <th width="20"></th>
            <th width="100">订单号</th>
            <th width="200">订单名称</th>
            <th width="80" class="tar">应收</th>
            <th width="80" class="tar">已收</th>
            <th width="80" class="tar">未收</th>
            <th width="200" class="tal">订购单位</th>
            <th width="70">部门</th>
            <th width="80" class="tar">收入</th>
            <th width="80" class="tar">支出</th>
            <th width="70">操作人</th>
            <th>备注</th>
            <th width="40">状态</th>
          </tr>
        </tbody>
        <tbody v-for="(list, index) in accountFlowList.optionList" :key="index">
          <tr :class="[index % 2 == 0 ? 'listBg' : 'cor', data.accountFlowId == list.id ? 'selected' : '']" @click="showTrAccountFlowByAccountId(list.id, list.accountId)">
            <td>{{ index + 1 }}</td>
            <td class="tal">{{ list.orderId }}</td>
            <td class="text-left">{{ list.travelLine }}</td>
            <td class="text-red-500 text-right">{{ toNumber(list.ygs) }}</td>
            <td class="text-blue-500 text-right">{{ toNumber(list.yjs) }}</td>
            <td class="text-red-500 text-right">{{ toNumber(list.wsk) }}</td>
            <td class="text-left">{{ list.sfmc }}</td>
            <td class="text-center">{{ list.ddlxZw }}</td>
            <td class="text-red-500 text-right">{{ toNumber(list.skje) }}</td>
            <td class="text-green-500 text-right">{{ toNumber(list.fkje) }}</td>
            <td>{{ list.lrr }}</td>
            <td class="text-left">{{ list.bz }}</td>
            <td>{{ list.statZw }}</td> 
          </tr>
          <!-- @click="showTRclick(isshow)" -->
        </tbody>
        <tfoot>
          <tr>
            <td>&nbsp;</td>
            <td class="tips">小计</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td class="tips text-red-500 text-right font-600" id="sumskje">{{ accountFlowList.sumskje }}</td>
            <td class="tips text-green-500 text-right font-600" id="sumfkje">{{ accountFlowList.sumfkje }}</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
        </tfoot>
      </table>

      <table class="orderTable" id="acctable"> 
        <thead>
          <tr>
            <th colspan="14" class="bg-green-50">
              <span class="float-left w-200px leading-30px">收支项目</span>
            </th>
          </tr>
        </thead> 
        <tbody>
          <tr class="listBg">
            <th width="20"></th>
            <th width="100">订单号</th>
            <th width="200">订单名称</th>
            <th width="80" class="tar">应收</th>
            <th width="80" class="tar">已收</th>
            <th width="80" class="tar">未收</th>
            <th width="200" class="tal">订购单位</th>
            <th width="70">部门</th>
            <th width="80" class="tar">收入</th>
            <th width="80" class="tar">支出</th>
            <th width="70">操作人</th>
            <th>备注</th>
            <th width="40">状态</th>
          </tr>
        </tbody>
        <tbody v-for="(list, index) in accountList.optionList" :key="index">
          <tr :class="[index % 2 == 0 ? 'listBg' : 'cor', data.accountFlowAccountIds.indexOf(list.id) >= 0 ? 'selected' : '']">
            <td>{{ index + 1 }}</td>
            <td class="payshoworder" v-if="accountFlow.sflx == '2'" @click="businessAccountTable(list.businessId, list.id)">{{ list.orderId }}</td>
            <td class="tal" v-else>{{ list.orderId }}</td>
            <td class="text-left">{{ list.travelLine }}</td>
            <td class="text-red-500 text-right">{{ toNumber(list.ygs) }}</td>
            <td class="text-blue-500 text-right">{{ toNumber(list.yjs) }}</td>
            <td class="text-red-500 text-right">{{ toNumber(list.wsk) }}</td>
            <td class="text-left">{{ list.sfmc }}</td>
            <td class="text-center">{{ list.ddlxZw }}</td>
            <td class="text-red-500 text-right">{{ toNumber(list.skje) }}</td>
            <td class="text-green-500 text-right">{{ toNumber(list.fkje) }}</td>
            <td>{{ list.lrr }}</td>
            <td class="text-left">{{ list.bz }}</td>
            <td>{{ list.statZw }}</td> 
          </tr>
          <!-- @click="showTRclick(isshow)" -->
        </tbody>
        <tfoot>
          <tr>
            <td>&nbsp;</td>
            <td class="tips">小计</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td class="tips text-red-500 text-right font-600" id="sumskje">{{ accountList.sumskje }}</td>
            <td class="tips text-green-500 text-right font-600" id="sumfkje">{{ accountList.sumfkje }}</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
        </tfoot>
      </table>
    </div>

    <!--银行流水 2025-08-25 qindl---->
    <div class="listtab1" id="con_menu_2" v-if="data.bankRunnigShow">
      <table class="orderTable" id="brtable">
        <thead>
          <tr>
            <th colspan="14" class="bg-blue-50">
              <span class="float-left w-200px leading-30px">银行流水</span>
              <span class="float-right text-right w-220px mr-1" v-if="accountFlow.sflx == '1'">
                <a-button id="addButton" color="success" @click="handleBankRunningAdd" :disabled="accountFlow.sffs == '4'"> 添加 </a-button>
              </span>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr class="listBg">
            <th width="100">记账时间</th>
            <th width="150">收支账户</th>
            <th width="220">对方账户</th>
            <th width="220">对方户名</th>
            <th width="80">收入</th>
            <th width="80">支出</th> 
            <th width="">备注</th>
          </tr>
        </tbody>
        <tbody v-for="(list, index) in bankRunningList.optionList" :key="index">
          <tr :class="[index % 2 == 0 ? 'listBg' : 'cor', data.bankRunningId == list.id ? 'selected' : '']" @click="selectBrTable(index, list.id)">
            <td>{{ list.jzsj }}</td>
            <td class="text-left">{{ list.djm }}</td>
            <td class="text-left">{{ list.dfzh }}</td>
            <td class="text-left">{{ list.dfhm }}</td>
            <td class="text-red-500 text-right">{{ toNumber(list.srje) }}</td>
            <td class="text-green-500 text-right">{{ toNumber(list.zcje) }}</td>
            <td class="text-left">{{ list.bz }}</td>
            <td style="display: none">{{ list.id }}</td>
          </tr>
        </tbody>
        <!--tbody v-if="bankRunning.optionList && bankRunning.optionList.length == 0" >
        <tr><td colspan="7" class="text-red-500">请先录入银行流水信息中心！</td></tr>
        </tbody-->
      </table>
    </div>

    <!--分解流水 2024-03-03 qindl---->
    <div class="listtab1" id="con_menu_2" v-if="data.bankBalanceShow">
      <table class="orderTable" id="brfjtable">
        <thead>
          <tr>
            <th colspan="14" class="bg-orange-50">
              <span class="float-left w-200px leading-30px">分解流水</span>
              <span class="float-right leading-30px current-stat">
                <span>已分解：</span><label class="font-bold text-red-500 mr-6">{{toNumber(bankBalanceList.sumskje)}}</label>
                <span>未分解：</span><label class="font-bold text-green-500 mr-2">{{toNumber(accountFlow.jePid - bankBalanceList.sumskje)}}</label>
              </span>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr class="listBg">
            <th width="100">记账时间</th>
            <th width="150">收支账户</th>
            <th width="220">对方账户</th>
            <th width="220">对方户名</th>
            <th width="80">收入</th>
            <th width="80">支出</th>
            <th width="">备注</th>
            <th width="40">状态</th>
          </tr>
        </tbody>
        <tbody v-for="(list, index) in bankBalanceList.optionList" :key="index">
          <tr :class="[index % 2 == 0 ? 'listBg' : 'cor', data.bankRunningPid == list.id ? 'selected' : '']" >
            <td>{{ list.jzsj }}</td>
            <td class="text-left">{{ list.djm }}</td>
            <td class="text-left">{{ list.dfzh }}</td>
            <td class="text-left">{{ list.dfhm }}</td>
            <td class="text-right text-red-500">{{ toNumber(list.srje) }}</td>
            <td class="text-right text-green-500">{{ toNumber(list.zcje) }}</td>
            <td class="text-left">{{ list.bz }}</td>
            <td>{{ list.shbj == '0' ? '未审' : '已审'}}</td> 
            <td style="display: none">{{ list.id }}</td>
          </tr>
        </tbody> 
        <!--tbody v-if="!bankBalanceList.hasOwnProperty('optionList')" >
          <tr><td colspan="7" class="text-red-500">未有分解数据！</td></tr>
        </tbody-->
      </table>
    </div>
    <!------>

    <!--订单收支 2025-08-25 qindl---->
    <div class="listtab1" id="con_menu_3" v-if="data.accountTableShow">
      <table class="orderTable" id="accounttable">
        <thead><tr> <th colspan="12"> 收付项目 </th> </tr></thead>
        <tbody>
          <tr class="listBg">
            <th width="60">状态</th>
            <th width="60">类型</th>
            <th width="70">支付方式</th>
            <th width="260">收付名称</th>
            <th width="80">部门</th>
            <th width="80">收入</th>
            <th width="80">支出</th>
            <th width="80">收支银行</th>
            <th width="100">收付时间</th>
            <th width="90">操作人</th>
            <th>备注</th>
            <th width="100">审核时间</th>
            <th width="70">审核人</th>
          </tr>
        </tbody>
        <tbody v-for="(list, index) in businessAccountList.optionList" :key="index">
          <tr :class="index % 2 == 0 ? 'listBg' : 'cor'">
            <td :class="list.stat == 3 ? 'text-red-500' : ''">{{ list.statZw }}</td>
            <td>{{ list.sflxZw }}</td>
            <td :class="list.sffs == 3 ? 'text-red-500' : ''">{{ list.sffsZw }}</td>
            <td class="text-left">{{ list.sfmc }}</td>
            <td>{{ list.ddlxZw }}</td>
            <td class="text-right text-red-500">{{ toNumber(list.skje) }}</td>
            <td class="text-right text-green-500">{{ toNumber(list.fkje) }}</td>
            <td>{{ list.bankdjm }}</td>
            <td>{{ list.sfsj }}</td>
            <td>{{ list.lrr }}</td>
            <td class="text-left">{{ list.bz }}</td>
            <td>{{ list.shsj }}</td>
            <td>{{ list.shrName }}</td>
          </tr>
        </tbody>
        <tfoot>
          <tr>
            <td>&nbsp;</td>
            <td class="tips">小计</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td class="tips align--right fwb text-red-500">{{ toNumber(businessAccountList.sumskje) }}</td>
            <td class="tips align--right fwb text-green-500">{{ (businessAccountList.sumfkje) }}</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
        </tfoot>
      </table>
    </div>
  </div>
  </BasicModal>
  <!--https://segmentfault.com/a/1190000039951044?utm_source=sf-similar-article @ok="bankRunningOk" @ok="flowPayOk"-->
  <AccountFlowBackReason @register="registerAccountFlowBackReason" @success="handleDeleteRecord"></AccountFlowBackReason>
  <AccountFlowPayModal @register="registerAccountFlowPay" @success="flowPayFinaceOk"></AccountFlowPayModal>
  <BankRunningModal @register="registerBankRunning" @success="bankRunningOk"></BankRunningModal>

  <BusinessOrder @register="registerBusinessOrder"></BusinessOrder>
</template>
<script lang="ts" setup>
  import '/@/design/order.css';
  import { ref, computed, unref, onMounted, reactive } from 'vue';
  import { BasicModal, useModal, useModalInner } from '/@/components/Modal';
  import {
    getRecordById,
    audit,
    loadAccount,
    loadAccountFlow,
    collateRecordJson,
    deleteRecordJson,
    rollbackRecord,
    loadBankRunning,
    loadBankBalance,
  } from '../types/accountflow.api';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { filterObj } from '/@/utils/common/compUtils';
  import AButton from '/@/components/Button/src/BasicButton.vue';
  import AccountFlowPayModal from './AccountFlowPayModal.vue';
  import AccountFlowBackReason from './AccountFlowBackReason.vue';
  import BankRunningModal from '/@/views/full/bank/modules/BankRunningModal.vue';
  import BusinessOrder from '/@/views/full/business/BusinessOrder.vue';
  import moment from 'dayjs';

  /**
   * 1、提交信息
   * 2、收支明细
   * 3、银行流水
   * 4、按钮显示
   * 5、按钮操作
   */
  const { createMessage: $message } = useMessage();
  // 声明Emits
  const emit = defineEmits(['success', 'register']);

  let accountFlow     = reactive<any>({}); //业务信息
  let accountFlowList = reactive<any>({}); //业务收支明细
  let accountList     = reactive<any>({}); //业务收支明细
  let businessAccountList = reactive<any>({}); //订单收支明细
  let bankRunningList     = reactive<any>({}); //银行流水
  let bankBalanceList     = reactive<any>({}); //分解流水
  let isReload = ref(false); //是否有数据操作
  let loading  = ref(true); //
  //界面控制数据
  let data = reactive({
    idArray: [], //数据数组
    idIndex: 0, //当前位置
    type: '', //业务类型
    stats: {}, //当前数据状态
    auditRecord: {}, //已审核数据
    listSize: 0, //数组总数
    intCheckValue: 0,
    intDeleteValue: 0,
    accountId: '',
    bankRunningId: '',
    bankRunningPid: '',
    accountFlowId: '',
    accountFlowAccountIds: '',
    payfinaceDisable: false,  //支付
    cwshButtonDisable: true,  //审核
    cwshButtonShow: false,    //审核
    rollbackDisable: false,   //取消
    rollbackShow: false,      //取消
    cwhtButtonDisable: false, //回退
    cwhtButtonShow: true, //回退
    payfinaceShow: false, //支付
    bankRunnigShow: false, //银行流水
    bankBalanceShow: false, //分解流水
    accountTableShow: false, //收支明细
  });

  //界面控制数据
  let bankRunningForm = reactive<any>({
    bankId: '',
    sflx: '',
    jzsj: '',
    je: 0,
  });

  //银行分解数据
  let bankBalanceModel = reactive<any>({
    djm: '',
    jzsj: '',
    sflxZW: '',
    zje: 0,
    yfje: 0,
    wfje: 0,
  });

  const getTitle = computed(() => {
    let title = '';
    if (data.type == 'takeFinaneChecked') {
      title = '收款审核';
    } else if (data.type == 'payFinaneChecked') {
      title = '转账支付';
    } else if (data.type == 'takePayment') {
      title = '挂账支付';
    } else if (data.type == 'takePayment') {
      title = '经理审批';
    } else if (data.type == 'takeManageChecked') {
      title = '挂账审批';
    } else if (data.type == 'payManageChecked') {
      title = '转账审核';
    }
    return title;
  });

  //1未审、2经理、3已审、9回退
  const statClass = computed(() => {
    let color = '#666';
    if (data.stats['stat'] == '1') {
      color = '#10b981'; //绿色
    } else if (data.stats['stat'] == '2') {
      color = '#8B008B'; //红
    } else if (data.stats['stat'] == '3') {
      color = '#ff0808'; //红
    } else if (data.stats['stat'] == '9') {
      color = '#333';
    }
    return color;
  });

  //表单赋值
  const [registerModal, { closeModal }] = useModalInner(async (data) => {
    await init(data);
  });

  //TODO---------数据初始化--------------------------------------------------------------------
  function setIdArray(array) {
    data.idArray = array && array.split(',');
    if (array == null || array == '') {
      data.listSize = 0;
    } else {
      data.listSize = data.idArray?.length;
    }
  }

  function init(record) {
    if (!record.id) {
      $message.warning('订单编号不能为空!');
      return;
    }
    loading.value = true;
    audit(filterObj(record)).then((res) => {
      try {
        if (res.success != true) {
          $message.warning(res.message);
          return false;
        }
        let result = res.result;
        setIdArray(result.idArray);
        data.type = result.type;
        data.idIndex = result.idIndex;
        getNextRecord();
      } catch (e) {
        $message.error('initData : ' + e);
        return false;
      }
    }).finally(() => {
      //data.loading = false
    });
  }

  //上一条
  function getUpRecord() {
    //$(':button').attr('disabled', 'true')
    var indexNum = data.idIndex;
    if (indexNum == null) {
      $message.warning('上一条 -> 数据下标有误！');
      refreshBtn();
      return;
    } else if (indexNum == -1 || indexNum == 0) {
      $message.warning('已经是第一条数据');
      refreshBtn();
      return;
    }
    var id = data.idArray[indexNum - 1];
    loading.value = true;
    getRecordById({ id: id }).then((res) => {
      if (res.success) {
        let result = res.result;
        data.idIndex = indexNum - 1;
        clearData();
        setBean(result);
      } else {
        $message.warning(res.message);
      }
    }).catch((error) => {
      console.error(error);
    }).finally(() => {
      refreshBtn();
      loadAccoutFlowList();
      loadAccoutList();
    });
  }

  //下一条
  function getNextRecord() {
    //$(":button").attr("disabled", true);
    var indexNum = data.idIndex; //下标
    if (data.listSize == 0) {
      $message.warning('数据已经审核完毕,未查询到下一条数据');
      //removeMask();
      return;
    }
    indexNum = Number(indexNum) + 1;
    if (indexNum >= data.listSize) {
      $message.warning('已经是最后一条数据');
      refreshBtn();
      //removeMask();
      return;
    }
    loading.value = true;
    var id = data.idArray[indexNum];
    getRecordById({ id: id }).then((res) => {
      if (res.success) {
        let result = res.result;
        data.idIndex = indexNum;
        //$("#_intIndexNum").text(indexNum + 1);	// 设置显示当前条数
        //$("#_indexNum").attr("value", Number(indexNum));	// 设置当前数据下标数值
        clearData();
        setBean(result);
      } else {
        $message.warning(res.message);
      }
    })
    .catch((error) => {
      console.error(error);
    })
    .finally(() => {
      refreshBtn();
      loadAccoutFlowList();
      loadAccoutList();
    });
  }

  async function setBean(jsonObj) {
    try {
      accountFlow.id  = jsonObj.id;
      accountFlow.lsh = jsonObj.lsh;
      accountFlow.orderId = jsonObj.orderId;
      accountFlow.lrr  = jsonObj.lrr;
      accountFlow.lrsj = jsonObj.lrsj;
      accountFlow.skje = jsonObj.skje;
      accountFlow.fkje = jsonObj.fkje;
      accountFlow.sksj = jsonObj.sksj;
      accountFlow.djm  = jsonObj.djm;
      accountFlow.shrName = jsonObj.shrName;
      accountFlow.shsj    = jsonObj.shsj;
      accountFlow.sprName = jsonObj.sprName;
      accountFlow.spsj = jsonObj.spsj;
      accountFlow.sflx = jsonObj.sflx;
      accountFlow.backReason = jsonObj.backReason;
      accountFlow.dfhm = jsonObj.dfhm;
      accountFlow.ddlx = jsonObj.ddlx;
      accountFlow.bz   = jsonObj.bz;
      accountFlow.uncouple = jsonObj.uncouple;

      data.stats['stat'] = jsonObj.stat;
      data.accountId     = jsonObj.accountId;

      accountFlow.intStat = jsonObj.statZw;
      accountFlow.intSffs = jsonObj.sffsZw;
      accountFlow.intSflx = jsonObj.sflxZw;

      //需要提交
      accountFlow.bankId  = jsonObj.bankId;
      accountFlow.ywlx    = jsonObj.sflx;
      accountFlow.sffs    = jsonObj.sffs;
      accountFlow.br_sksj = jsonObj.sksj;

      //qindl 2024-03-02
      accountFlow.djmPid = jsonObj.djmPid;
      accountFlow.jePid  = jsonObj.jePid;
      var bankId = jsonObj.bankId;
      var je = jsonObj.je;

      if (jsonObj.sflx == '1' && jsonObj.sffs == '3') {
        // 收款，挂账
        bankId = jsonObj.bankPid;
        je = jsonObj.jePid;
        //录入银行流水表单
        bankRunningForm.bankId = jsonObj.bankPid;
        bankRunningForm.sflx = jsonObj.sflx;
        bankRunningForm.je = jsonObj.jePid;
        bankRunningForm.jzsj = jsonObj.sksj;
        data.bankBalanceShow = true;
        //已审核银行流水
        data.bankRunningId = jsonObj.bankRunningPid;
        data.bankRunningPid = jsonObj.bankRunningId;
      } else {
        //录入银行流水表单
        bankRunningForm.bankId = jsonObj.bankId;
        bankRunningForm.sflx = jsonObj.sflx;
        bankRunningForm.je = jsonObj.je;
        bankRunningForm.jzsj = jsonObj.sksj;
        data.bankBalanceShow = false;
        //已审核银行流水
        data.bankRunningId = jsonObj.bankRunningId;
        data.bankRunningPid = jsonObj.bankRunningPid;
      }
      //------------------------------------
      
      //console.info("accountflowInterval@@@@", data.bankRunningId, data.bankRunningPid, (accountFlow.ywlx == '1' && accountFlow.sffs == '3'))
      if (accountFlow.ywlx == '1' && accountFlow.sffs == '3') {
        await loadBankRunnigList(jsonObj.bankRunningPid, bankId, jsonObj.sflx, jsonObj.sksj, je, jsonObj.sffs);

        let pid = jsonObj.bankRunningPid;
        if (jsonObj.stat != 3 && bankRunningList.optionList.length == 1) {
          //只有一条银行流水时，默认选中它
          pid = bankRunningList.optionList && bankRunningList.optionList[0].id;
          data.bankRunningId = pid;
        }
        await loadBankBalanceList(pid);
      } else {
        loadBankRunnigList(jsonObj.bankRunningId, bankId, jsonObj.sflx, jsonObj.sksj, je, jsonObj.sffs);
      }
    } catch (e) {
      //alert("setBean -> " + e.message)
      return;
    }
  }

  const sffsColor = computed( () => {
    if (accountFlow.sffs == '1') {
      return 'text-red-500'; //绿色
    } else if (accountFlow.sffs == '3') {
      return 'text-blue-500'; //红
    } else if (accountFlow.sffs == '4') {  
      return 'text-purple-500';
    } else {
      return '#666';
    }
  })

  /**
   * 2020-08-24 取消
   * 当收支项目走到，财务管理（收款审核、转账支付、挂账支付），财务需要回退重新操作
   */
  function handleRollbackRecord() {
    var indexNum = data.idIndex;
    if (indexNum == null) {
      $message.warning('请先选择收付待审核数据');
      refreshBtn();
      return;
    }
    var recheck = ''; //$("#_recheck").val();
    var type = data.type;
    var id = data.idArray[indexNum];
    var nextId = data.idArray[indexNum];

    var params = {
      id: id,
      nextId: nextId,
      recheck: recheck,
      type: type,
    };
    rollbackRecord(params)
    .then((res) => {
      //$message.warning(res.message)
      if (res.success == true) {
        var msg = res.result;
        if (msg != '') {
          data.idIndex = indexNum;
          setBean(msg);
        } else {
          refreshBtn();
          $message.warning('数据已经审核完毕,未查询到下一条数据');
        }
        if (typeof data.auditRecord['_' + id] == 'undefined') {
          // 未审核
          data.intCheckValue++;
        } else if (data.auditRecord['_' + id] == 1) {
          // 已通过
          data.intCheckValue--;
          data.intCheckValue++;
        }
        data.auditRecord['_' + id] = 0; // 标记为作废

        //2021-10-25 qindl
        $message.success(' 操作成功！');
      } else {
        $message.warning(res.message);
        return false;
      }
    })
    .finally(() => {
      refreshBtn();
      loadAccoutFlowList();
      loadAccoutList();
      isReload.value = true;
    });
  }

  //根据ID加载操作日志 2\收付项目
  function loadAccoutList() {
    //debugger;
    //清空
    var account_ids = data.accountId;
    if (account_ids == '' || account_ids == null) {
      return false;
    }
    var params = {  };
    if (accountFlow.uncouple == '1') {
      params = {
        parentId: accountFlow.id,
        uncouple: accountFlow.uncouple 
      }
    } else {
      params = { 
        account_ids: account_ids,
        uncouple: accountFlow.uncouple 
       };
    }
    loadAccount(params).then((res) => {
      if (res.success != true) {
        //this.$message.warning(res.message)
        return false;
      }
      Object.assign(accountList, res.result);
    });
  }

  //根据ID加载操作日志 2\收付项目
  function loadAccoutFlowList() {
    // 合并类型
    if (accountFlow.uncouple != '1') {
      return false;
    }
    //清空
    var parentId = accountFlow.id;
    if (parentId == '' || parentId == null) {
      return false;
    }
    var params = { parentId: parentId };
    loadAccountFlow(params).then((res) => {
      if (res.success != true) {
        //this.$message.warning(res.message)
        return false;
      }
      Object.assign(accountFlowList, res.result);
    });
  }

  /**
   * 查看 订单详情
   * 作者：qdl
   * 日期：2023-05-23
   */
  //详细订单
  const [registerBusinessOrder, { openModal: openBusinessOrder }] = useModal();
  //双击行
  function handleDblclick(data) {
    openBusinessOrder(true, data);
  }

  //收款 ------------------------------------------------
  function businessAccountTable($orderId, $id) {
    //$("#con_menu_3").show();
    var params = { id: $orderId, oAccountId: $id, buttonAll: false };
    handleDblclick(params);
  }

  //点击选择银行流水
  function selectBrTable(index, id) {
    // 状态：3已审｜9回退 || data.stats['stat'] == 9
    if (data.stats['stat'] == 3) {
      console.info('当前状态不可以操作！' + data.stats['stat']);
      return;
    }

    // 选中流水编号
    if (!data.bankRunningId || data.bankRunningId != id) {
      data.bankRunningId = id;
      data.cwshButtonDisable = false;
    } else {
      data.bankRunningId = '';
      data.cwshButtonDisable = true;
    }
    
    let jsonObj = accountFlow;
    if (jsonObj.sflx == '1' && jsonObj.sffs == '3') {
      //需要提交
      bankRunningForm.bankId = jsonObj.bankPid;
      bankRunningForm.sflx = jsonObj.sflx;
      bankRunningForm.je = jsonObj.jePid;
      bankRunningForm.jzsj = jsonObj.sksj;
    } else {
      //需要提交
      bankRunningForm.bankId = jsonObj.bankId;
      bankRunningForm.sflx = jsonObj.sflx;
      bankRunningForm.je = jsonObj.je;
      bankRunningForm.jzsj = jsonObj.sksj;
    }

    loadBankBalanceList(data.bankRunningId);
      //------------------------------------
  }

  //TODO---------审核操作--------------------------------------------------------------------
  //通过 审核 + 支付
  function handleCollateRecord() {
    loading.value = true;
    if (data.stats['stat'] == 3) {
      $message.warning('该数据财务已审核!');
      refreshBtn();
      return;
    }
    //$(':button').attr('disabled', 'true') || indexNum === ''
    var indexNum = data.idIndex;
    if (indexNum == null) {
      $message.warning('请先选择审核信息');
      refreshBtn();
      return;
    }
    indexNum = Number(indexNum);

    var type = data.type;
    if (type == null || type == '') {
      $message.warning('TYPE值为空，数据异常请联系管理员');
      refreshBtn();
      return;
    }

    var bankRunningId = data.bankRunningId;
    if (type == 'takeFinaneChecked' && (bankRunningId == null || bankRunningId == '')) {
      $message.warning('收款审核，请先选择银行流水数据');
      refreshBtn();
      return;
    }

    var recheck = ''; //$('#_recheck').val() 不知道有什么用
    var id = data.idArray[indexNum];
    var nextId = data.idArray[indexNum];

    var params = {
      id: id,
      bankRunningId: bankRunningId || '',
      nextId: nextId,
      recheck: recheck,
      type: type,
      bankId: bankRunningForm.bankId,
      fkje: bankRunningForm.je,
      jzsj: bankRunningForm.jzsj,
      dfzh: bankRunningForm.dfzh,
      dfhm: bankRunningForm.dfhm,
    };

    collateRecordJson(params).then((res) => {
      if (res.success == true) {
        var msg = res.result;
        if (msg != '') {
          data.idIndex = indexNum;
          setBean(msg);
        } else {
          $message.warning('数据已经审核完毕,未查询到下一条数据');
        }
        // 未审核
        if (typeof data.auditRecord['_' + id] == 'undefined') {
          data.intCheckValue++;
        } else if (data.auditRecord['_' + id] == 1) {
          // 已通过
          data.intCheckValue--;
          data.intCheckValue++;
        }
        // 标记为作废
        data.auditRecord['_' + id] = 0;

        $message.success(' 操作成功！');
      } else {
        //this.$notification.warning({ message: res.message })
        $message.warning(res.message);
        return false;
      }
    }).finally(() => {
      refreshBtn();
      loadAccoutFlowList();
      loadAccoutList();
      isReload.value = true;
    });
  }

  /**
   * 回退原因 提交触发
   * 作者：qdl
   * 日期：2023-02-23
   */
  const [registerAccountFlowBackReason, { openModal: accountFlowBackReasonModal }] = useModal();
  function handleBackReasonModal() {
    var indexNum = data.idIndex;
    if (indexNum == null) {
      $message.warning('请先选择收付待审核数据');
      refreshBtn();
      return;
    }
    accountFlowBackReasonModal();
  }

  //回退 - 确认
  function handleDeleteRecord() {
    //$(':button').attr('disabled', 'true')
    loading.value = true;
    var indexNum = data.idIndex;
    if (indexNum == null) {
      $message.warning('请先选择收付待审核数据');
      refreshBtn();
      return;
    }

    //var recheck = $('#_recheck').val()
    var recheck = '';
    var type = data.type;

    indexNum = Number(indexNum);
    var id = data.idArray[indexNum];
    var nextId = data.idArray[indexNum];

    var params = {
      id: id,
      nextId: nextId,
      recheck: recheck,
      type: type,
    };

    deleteRecordJson(params).then((res) => {
      if (res.success == true) {
        var msg = res.result;
        if (msg != '') {
          data.idIndex = indexNum;
          clearData();
          setBean(msg);
          //2025-09-15 qindl
          $message.success(' 操作成功！');
        } else {
          refreshBtn();
          $message.warning('数据已经审核完毕,未查询到下一条数据');
        }
        if (typeof data.auditRecord['_' + id] == 'undefined') {
          // 未审核
          data.intDeleteValue++;
        } else if (data.auditRecord['_' + id] == 1) {
          // 已通过
          data.intDeleteValue--;
          data.intDeleteValue++;
        }
        data.auditRecord['_' + id] = 0; // 标记为作废
      } else {
        $message.warning(res.message);
        return false;
      }
    }).finally(() => {
      refreshBtn();
      loadAccoutFlowList();
      loadAccoutList();
      isReload.value = true;
    });
  }

  /**
   * 列表-银行流水
   * @param id 
   * @param sflx 收付类型
   * @param sffs 收付方式
   * @param jzsj 记账日期
   * @param bankId 记账银行
   * @param je 记账金额
   * @param bankPid 入账金额
   * @param jePid 入账金额
   */
  async function loadBankRunnigList(id, bankId, sflx, jzsj, je, sffs) {
    refreshBankRunningList();
    var type = data.type;
    if (type == 'takeFinaneChecked' || type == 'takeFinaneRechecked') {
      data.bankRunnigShow = true;
    } else {
      data.bankRunnigShow = false;
      return false;
    }
    if ((typeof bankId == 'undefined' || bankId == '') && (typeof jzsj == 'undefined' || jzsj == '')) {
      return false;
    }
    var params = {
      id: id,
      bankId: bankId,
      sflx: sflx,
      jzsj: jzsj,
      je: je,
      sffs: sffs
    };
    await loadBankRunning(params).then((res) => {
      if (res.success != true) {
        $message.warning(res.message);
        return false;
      }
      Object.assign(bankRunningList, res.result);
      //console.info("bankRunningList@@", bankRunningList)
    });
  }

  /**
   * 列表-银行流水-显示已审核银行流水-收款挂账
   * @param id 
   */
  function loadBankBalanceList(id) {
    refreshBankBalanceList();
    if (typeof id == 'undefined' || id == '' || id == null) {
      return false;
    }
    var params = {
      id: id,
    };
    loadBankBalance(params).then((res) => {
      if (res.success != true) {
        $message.warning(res.message);
        return false;
      }
      Object.assign(bankBalanceList, res.result);
      //console.info("bankBalanceList@@", bankBalanceList);
    });
  }

  /**
   * 列表-银行流水-显示已审核银行流水-收款挂账
   */
  function showTrAccountFlowByAccountId(id, account_ids) {
    if (data.accountFlowId == id) {
      data.accountFlowId = "";
      data.accountFlowAccountIds = '';
      return false;
    }

    data.accountFlowId = id;
    data.accountFlowAccountIds = account_ids;
  }

  /**
   * 刷新重置按钮
   * 1、按钮：审核 （转账审核：直接可用； 收款审核：需要点选银行流水）
   * 2、按钮：取消 （隐藏，只有转账支付、挂账支付，账务审核后才显示）
   * 3、银行流水： （转账支付才显示）
   * 4、收支明细： （转账支付，点订单编号才显示）
   */
  function refreshBtn() {
    var type = data.type;
    loading.value = false;
    data.rollbackShow = false; //撤销
    data.accountTableShow = false;
    data.accountFlowId = '';
    data.accountFlowAccountIds = '';
    if (type == 'viewData') {
      data.cwhtButtonDisable = false;
      data.cwshButtonDisable = true;
    } else if (type == 'payFinaneChecked' || type == 'takePayment') {
      //2、状态：2经理；3已审；9回退；payFinaneChecked（ 转账支付）、takePayment（挂账支付）
      data.payfinaceShow = true; //支付
      data.cwshButtonShow = false; //审核
      if (data.stats['stat'] == '3') {
        //3已审
        data.cwhtButtonDisable = false;
        data.payfinaceDisable = true;
        data.payfinaceShow = true; //支付
        data.rollbackShow = true; //撤销
      } else if (data.stats['stat'] == '9') {
        data.payfinaceDisable = false;
        data.cwhtButtonDisable = true;
      } else {
        data.payfinaceDisable = false;
        data.cwhtButtonDisable = false;
      }
    } else {
      //2、状态：2经理；3财务；9回退
      data.payfinaceShow = false;
      data.cwshButtonShow = true;
      if (data.stats['stat'] == '2' || data.stats['stat'] == '3') {
        data.cwhtButtonDisable = false;
        data.cwshButtonDisable = true;
      } else if (data.stats['stat'] == '9') {
        data.cwshButtonDisable = false;
        data.cwhtButtonDisable = true;
      } else {
        data.cwshButtonDisable = false;
        data.cwhtButtonDisable = false;
      }
    }
  }

  function refreshBankRunningList() {
    Object.assign(bankRunningList, {sumskje: '0.00', optionList: [], sumfkje: '0.00'});
  }

  function refreshBankBalanceList() {
    Object.assign(bankBalanceList, {sumskje: '0.00', optionList: [], sumfkje: '0.00'});
  }

  /**
   * 银行流水 注册弹出编辑窗口
   * 作者：qdl
   * 日期：2022-06-28
   */
  const [registerBankRunning, { openModal: bankRunningModal }] = useModal();

  /**
   * 银行流水 打开添加编辑窗口
   * 作者：qdl
   * 日期：2022-06-28
   */
  function handleBankRunningAdd() {
    let record = Object.assign({}, bankRunningForm);
    bankRunningModal(true, { record, isUpdate: false });
  }

  /**
   * 银行流水 提交触发
   * 作者：qdl
   * 日期：2022-06-28
   */
  function bankRunningOk() {
    loadBankRunnigList('', bankRunningForm.bankId, bankRunningForm.sflx, bankRunningForm.jzsj, bankRunningForm.je, bankRunningForm.sffs);
  }

  /**
   * 银行流水 注册弹出编辑窗口
   * 作者：qdl
   * 日期：2022-06-28
   */
  const [registerAccountFlowPay, { openModal: accountFlowPayModal }] = useModal();

  function flowPayModal() {
    var list = accountList.optionList;
    var je = 0;
    var sflx = accountFlow.sflx;
    if (sflx == '1') {
      je = accountFlow.skje;
    } else {
      je = accountFlow.fkje;
    }
    var dwmc = '';
    if (list != null && list.length > 0) {
      dwmc = list[0].sfmc;
    }
    var record = {
      sffs: accountFlow.sffs,
      dwmc: dwmc,
      je: je || 0,
      bankId: bankRunningForm.bankId || '',
      jzsj: moment().format('YYYY-MM-DD'),
      ddlx: accountFlow.ddlx,
    };

    accountFlowPayModal(true, { record });
  }

  // 赋值数据前 - 清空对象
  function clearData() {
    // accountFlowList = reactive<any>({}); 
    // accountList     = reactive<any>({}); 
    // businessAccountList = reactive<any>({}); 
    // bankRunningList     = reactive<any>({}); //银行流水
    // bankBalanceList     = reactive<any>({}); //分解流水

    loading.value = true;

    //业务信息
    Object.keys(accountFlow).forEach( key => {
      delete accountFlow[key]
    })

    //业务收支明细
    Object.keys(accountFlowList).forEach( key => {
      delete accountFlowList[key]
    })

    //业务收支明细
    Object.keys(accountList).forEach( key => {
      delete accountList[key]
    })

    //订单收支明细
    Object.keys(bankRunningList).forEach( key => {
      delete bankRunningList[key]
    })

    Object.keys(bankBalanceList).forEach( key => {
      delete bankBalanceList[key]
    })
  }

  /**
   * 支付 提交触发
   * 作者：qdl
   * 日期：2022-06-28
   */
  function flowPayFinaceOk(data) {
    bankRunningForm.bankId = data.bankId;
    bankRunningForm.je = data.je;
    bankRunningForm.jzsj = data.jzsj;
    handleCollateRecord();
  }

  // Cancel event
  function onClose() {
    if (isReload.value) {
      emit('success', isReload);
    }
  }

  function toNumber(v) {
    let n = 0;
    if (v) {
      n = v;
    }
    return Number(n).toFixed(2);
  }
</script>
<style lang="less" scoped></style>
